package cn.wei.reallyEnjoy.app;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.wei.reallyEnjoy.R;
import cn.wei.reallyEnjoy.user.activity.WriteDiaryActivity;
import cn.wei.reallyEnjoy.utils.Constants;
import okhttp3.Call;

public class RegisterActivity extends AppCompatActivity {

    private static int RESULT_LOAD_IMAGE = 10;
    private String imgUrl = "";
    @BindView(R.id.tv_register_black_title)
    TextView tv_register_black_title;
    @BindView(R.id.et_account)
    EditText et_account;
    @BindView(R.id.et_pass)
    EditText et_pass;
    @BindView(R.id.et_register_nickname)
    EditText et_register_nickname;
    @BindView(R.id.btn_register)
    Button btn_register;

    @BindView(R.id.iv_reg_user_img)
    ImageView ivRegUserImg;
    @BindView(R.id.btn_reg_user_selectImg)
    Button btnRegUserSelectImg;





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        //去掉窗口标题
        getSupportActionBar().hide();
        //ButterKnife和当前Activity绑定
        ButterKnife.bind(this);
        initListener();
    }

    private void initListener() {
        tv_register_black_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
        btnRegUserSelectImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击事件，而重定向到图片库
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                //android6.0之后不仅需要在Mainfest里面添加权限，还需要添加运行时权限。
                //这里要传一个整形的常量RESULT_LOAD_IMAGE到startActivityForResult()方法。
                //我们需要判断requestCode是否是我们之前传给startActivityForResult()方法的RESULT_LOAD_IMAGE，并且返回的数据不能为空
                if (ActivityCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(RegisterActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                }

                startActivityForResult(intent, RESULT_LOAD_IMAGE);
            }
        });
        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String mobile = et_account.getText().toString().trim();
                String password = et_pass.getText().toString().trim();
                String nickName = et_register_nickname.getText().toString().trim();
                if (TextUtils.equals(imgUrl,"")){
                    Toast.makeText(RegisterActivity.this, "请选择头像", Toast.LENGTH_SHORT).show();
                    return;
                }
                else if (TextUtils.isEmpty(mobile)){
                    Toast.makeText(RegisterActivity.this, "账号不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }else if (TextUtils.isEmpty(password)){
                    Toast.makeText(RegisterActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }else if (TextUtils.isEmpty(nickName)){
                    Toast.makeText(RegisterActivity.this, "昵称不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }


                String url = Constants.REGISTER_URL;
                OkHttpUtils
                        .post()
                        .url(url)
                        .addParams("mobile",mobile)
                        .addParams("password",password)
                        .addParams("nickName",nickName)
                        .addParams("headImg",imgUrl)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                Toast.makeText(RegisterActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                JSONObject jsonObject = JSON.parseObject(response);
                                System.out.println(jsonObject);
                                String code = (String) jsonObject.get("code");
                                String msg = (String) jsonObject.get("msg");
                                if (TextUtils.equals(code,"0")){
                                    new AlertDialog.Builder(RegisterActivity.this)
                                            .setTitle("提示")
                                            .setMessage("注册成功，去登录")
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    Intent intent=new Intent(RegisterActivity.this,LoginActivity.class); //使用getActivity得到当前Activity
                                                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                                    startActivity(intent);

                                                }
                                            })
                                            .setCancelable(false)
                                            .show();
                                }else{

                                    Toast.makeText(RegisterActivity.this, msg, Toast.LENGTH_LONG).show();
                                }

                            }
                        });
            }
        });

    }
    //重写启动新的activity以后的回调方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            //查询我们需要的数据
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            Log.e("picturePath",picturePath);

            String fileName = picturePath.split("/")[picturePath.split("/").length - 1];
            Log.e("fileName",fileName);
            cursor.close();
            ivRegUserImg.setImageBitmap(BitmapFactory.decodeFile(picturePath));
            String url = Constants.FILE_UPLOAD_URL;

            File file = new File(picturePath);
            OkHttpUtils.post()
                    .url(url)
                    .addFile("file", fileName, file)//
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Toast.makeText(RegisterActivity.this, "网络错误,图片上传失败", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            JSONObject jsonObject = JSON.parseObject(response);
                            String code = String.valueOf(jsonObject.get("code"));
                            if (TextUtils.equals(code,"0")){
                                imgUrl = String.valueOf(jsonObject.get("data"));
                                Log.e("imgUrl",imgUrl);
                                Glide.with(RegisterActivity.this).load(Constants.BASE_URL+imgUrl).into(ivRegUserImg);

                            }else{
                                Toast.makeText(RegisterActivity.this, "服务器错误,图片上传失败", Toast.LENGTH_SHORT).show();
                            }

                        }
                    });




        }


    }
}